<template>
  <div
    class="bi-wrapper fixed inset-0 flex flex-col w-screen h-screen overflow-hidden bg-[url('@/assets/bi_images/bg.png')] bg-no-repeat bg-center bg-[length:100%_100%] text-[var(--el-text-color-primary)]"
    ref="rootRef"
  >
    <header
      class="flex items-center justify-between h-[83px] px-20px bg-[url('@/assets/bi_images/header-bg.png')] bg-no-repeat bg-center bg-[length:100%_100%] border-b border-[var(--el-border-color)] font-['AlimamaShuHeiTi','Microsoft YaHei',sans-serif] w-full"
    >
      <div class="flex items-center w-full">
        <div class="text-30px !font-700 w-[25%] text-center cursor-pointer" @click="goHome">超前预警可视化系统</div>
        <div class="flex items-center ml-24px gap-16px">
          <div
            v-for="t in tabs"
            :key="t.key"
            class="px-14px py-8px rd-4px cursor-pointer select-none text-[#bfd3e5] transition-all duration-200 ease-in-out flex items-center justify-center font-700 hover:bg-white/5"
            :class="activeTab === t.key ? 'text-[#f6fcff] ' : ''"
            @click="switchTab(t.key)"
          >
            {{ t.label }}
          </div>
        </div>
      </div>
      <div class="flex items-center">
        <div>
          <el-dropdown class="cursor-pointer transition duration-300 hover:bg-white/5" trigger="click"
                       @command="handleCommand">
            <div class="relative flex items-center">
              <img :src="userStore.avatar" class="cursor-pointer w-40px h-40px rd-10px"/>
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <router-link to="/index">
                  <el-dropdown-item>返回首页</el-dropdown-item>
                </router-link>
                <router-link to="/user/profile">
                  <el-dropdown-item>个人中心</el-dropdown-item>
                </router-link>
                <el-dropdown-item divided command="logout">
                  <span>退出登录</span>
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
    </header>

    <main class="relative flex-1 min-h-0 w-full h-[calc(100vh-83px)] overflow-hidden py-24px px-53px pb-40px">
      <transition name="drill-fade" mode="out-in">
        <div v-if="!showDrill" key="overview" class="h-full">
          <component :is="compMap[activeTab]" @show-drill="handleShowDrill"/>
        </div>
        <div v-else key="drill" class="h-full">
          <RiskIndexDrillDown class="h-[calc(100%-72px)]" :selected-category="selectedCategory"
                              @hide-drill="handleHideDrill"/>
        </div>
      </transition>
    </main>
  </div>
</template>

<script setup lang="ts">
import {type ComponentInternalInstance, getCurrentInstance, onBeforeUnmount, onMounted, ref, watch} from 'vue';
import {useUserStore} from '@/store/modules/user';
import router from '@/router';
import {getTenantList} from '@/api/login';
import type {TenantVO} from '@/api/types';
import {ElMessageBox} from 'element-plus';
import RiskIndex from './components/RiskIndex.vue';
import KeyAlarmModel from './components/KeyAlarmModel.vue';
import BarrierIntegrityModel from './components/BarrierIntegrityModel.vue';
import RiskIndexDrillDown from './components/drill/RiskIndexDrillDown.vue';
import {useRoute} from 'vue-router';

const userStore = useUserStore();
const rootRef = ref<HTMLElement | null>(null);
const route = useRoute();
const enterpriseName = ref<string>('');
const tabs = [
  {key: 'risk', label: '安全管理指数'},
  {key: 'barrier', label: '屏障完好性预警'},
  {key: 'alarm', label: '关键工艺报警预警'},
] as const;
type TabKey = (typeof tabs)[number]['key'];
const activeTab = ref<TabKey>('risk');
const compMap = {
  risk: RiskIndex,
  alarm: KeyAlarmModel,
  barrier: BarrierIntegrityModel
} as const;

const showDrill = ref(false);
const selectedCategory = ref<string>('');
const tabKeys = tabs.map((item) => item.key) as TabKey[];

const {proxy} = getCurrentInstance() as ComponentInternalInstance;

// 进入大屏时启用全局暗黑模式，离开时恢复
onMounted(async () => {
  document.documentElement.classList.add('dark');
  await initEnterpriseName();
});

watch(
  () => route.query.tab,
  (tab) => {
    if (typeof tab === 'string' && (tabKeys as string[]).includes(tab)) {
      switchTab(tab as TabKey);
    }
    showDrill.value = false;
  },
  {immediate: true}
);

onBeforeUnmount(() => {
  document.documentElement.classList.remove('dark');
});

async function initEnterpriseName() {
  try {
    const {data} = await getTenantList(true);
    const list: TenantVO[] = data.voList || [];
    const cur = list.find((t) => String(t.tenantId) === String(userStore.tenantId));
    enterpriseName.value = cur?.companyName || '';
  } catch (e) {
    enterpriseName.value = '';
  }
}

// 下拉菜单命令
const commandMap: { [key: string]: () => void | Promise<void> } = {
  logout: async () => {
    try {
      await ElMessageBox.confirm('确定注销并退出系统吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      });
      await userStore.logout();
      router.replace({
        path: '/login',
        query: {
          redirect: encodeURIComponent(router.currentRoute.value.fullPath || '/')
        }
      });
      proxy?.$tab.closeAllPage?.();
    } catch (err) {
      // 取消或异常忽略
    }
  }
};

function handleCommand(command: string) {
  commandMap[command]?.();
}

function goHome() {
  router.push('/index');
}

function switchTab(tab: TabKey) {
  activeTab.value = tab;
  showDrill.value = false;
}

function handleShowDrill(category?: string) {
  if (activeTab.value === 'risk') {
    selectedCategory.value = category || '';
    showDrill.value = true;
  }
}

function handleHideDrill() {
  showDrill.value = false;
}
</script>
<style scoped lang="scss">
.bi-wrapper {
  header {
    font-family: 'Alimama ShuHeiTi', sans-serif !important;
  }

  /* 表格表头背景图片，主体透明 */
  :deep(.el-table__header-wrapper) {
    background-image: url('@/assets/bi_images/table-header-bg.png') !important;
    background-repeat: no-repeat;
    background-position: center;
    background-size: 100% 100%;
  }

  :deep(.el-table__header),
  :deep(.el-table__header tr),
  :deep(.el-table__header th),
  :deep(.el-table__header .el-table__cell) {
    color: #fff;
    background-color: transparent !important;
  }

  :deep(.el-table),
  :deep(.el-table__inner-wrapper),
  :deep(.el-table__body-wrapper),
  :deep(.el-table__body),
  :deep(.el-table__row),
  :deep(.el-table__cell) {
    color: #fff;
    background-color: transparent !important;
    border-bottom: 1px solid #1f4883 !important;
  }

  .drill-header {
    padding: 10px 12px;
    border: 1px solid rgba(67, 147, 235, 0.35);
    border-radius: 10px;
    background: linear-gradient(90deg, rgba(22, 66, 133, 0.55) 0%, rgba(16, 45, 93, 0.55) 100%);
  }

  .drill-back {
    color: #8ad2ff;
    font-size: 16px;

    &:hover {
      color: #fff;
    }
  }

  .drill-title {
    text-shadow: 0 0 12px rgba(90, 182, 255, 0.65);
  }

  .drill-placeholder {
    width: 90px;
  }

  .drill-fade-enter-active,
  .drill-fade-leave-active {
    transition: opacity 0.35s ease,
    transform 0.35s ease;
  }

  .drill-fade-enter-from,
  .drill-fade-leave-to {
    opacity: 0;
    transform: translateY(18px) scale(0.98);
  }

  .drill-fade-enter-to,
  .drill-fade-leave-from {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}
</style>
